/*
 项目名称：控制台版五子棋游戏的实现
 版权所有：剑影科技集团
 作    者：守护天使
 版    本：v 1.0

 项目描述：使用C语言实现控制台版五子棋游戏，支持两人对战
 备    注：今天是个好日子，带着大家编写第一个小项目
 */
#include <stdio.h>

//定义二维数组表示棋盘
int piece[16][16] = {};

//函数声明
void draw_box(void);
void play_piece(void);
int judge_piece(int player);
int main(void){
	draw_box();
	play_piece();
	return 0;
}

//绘制棋盘
void draw_box(void){
	//打印棋盘水平坐标
	int i = 0,j = 0;
	for(i = 0;i < 17;i++){
		if(0 == i) printf("  ");
		else printf("%x ",i-1);
	}
	printf("\n");
	//打印棋盘
	for(i = 0;i < 16;i++){
		printf("%x ",i);
		for(j = 0;j < 16;j++){
			if(piece[i][j] == 0) printf("* ");
			else if(piece[i][j] == 1) printf("@ ");
			else  printf("$ ");
		}
		printf("\n");
	}
}

//下棋函数
void play_piece(){
	int x = -1,y = -1,player = 0,i = 0;
	while (1){
		if(player == 0) {
			printf("请黑方出手\n");
			scanf("%d%d",&x,&y);
			if(piece[x][y] == 1||piece[x][y] == 2|| x > 15 || y > 15 || x < 0 || y < 0){
				//通过scanf的返回值处理！
				printf("该处已落子或超出范围请重新输入:\n");
				scanf("%*[^\n]");
				scanf("%*c");
				continue;
			}else piece[x][y] = 1;
			//重绘棋盘
			draw_box();
			//判断是否获胜
			if(judge_piece(player + 1)) {printf("黑方胜利了\n"); break;}
			player = 1;
		}else{
			printf("请白方出手\n");
			scanf("%d%d",&x,&y);
			if(piece[x][y] != 0 || x > 15 || y > 15 || x < 0 || y < 0){
				printf("该处已落子或超出范围请重新输入:\n");
				scanf("%*[^\n]");
				scanf("%*c");
				continue;
			}else piece[x][y] = 2;
				//重绘棋盘
				draw_box();
				if(judge_piece(player + 1)) {printf("白方胜利了\n"); break;}
				player = 0;
		}
	}	
}
//判断输赢
int judge_piece(int player){
	int i = 0,j = 0;
	for(i = 0;i < 16;i++){
		for(j = 0;j < 12;j++){
			//水平方向
			if((piece[i][j]&piece[i][j+1]&piece[i][j+2]&piece[i][j+3]&piece[i][j+4]) == player) return 1;
			//垂直方向
			if((piece[i][j]&piece[i+1][j]&piece[i+2][j]&piece[i+3][j]&piece[i+4][j]) == player) return 1;
			//右斜方向
			if((piece[i][j]&piece[i][j+17]&piece[i][j+34]&piece[i][j+51]&piece[i][j+68]) == player) return 1;
			//左斜方向
			if((piece[i][j]&piece[i][j+15]&piece[i][j+30]&piece[i][j+45]&piece[i][j+60]) == player) return 1;
		}
	}
	return 0;
}
